# -*- coding: utf-8 -*-
# 姓名:谚语
# 开发时间:2022/11/7 19:53
import datetime

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from comment.modules import db
from comment.modules.user import User
from comment.utils.decorators import login_required
from comment.modules.debt_repay import Debtor_repay
from financial.resources.transaction.seralizer import RepayPlanSerializer


class RepayPlan(Resource):
    """还款的资源类"""
    # 使用了登录拦截的装饰器[LoginOut整个资源的函数执行前都执行一次装饰器确认是否登录]
    method_decorators = [login_required]

    def get(self):
        """查询某一个(匹配成功的)债权所对应的还款计划"""
        # 定义
        rp = RequestParser()
        rp.add_argument('debt_id')  # 债权的id
        # 接收
        args = rp.parse_args()
        debt_id = int(args.get('debt_id'))

        # 债权还款的模型类查询过滤得到的一个债权还款列表
        repay_list = Debtor_repay.query.filter(Debtor_repay.claimsId == debt_id).all()
        # 还款计划的序列化
        data = RepayPlanSerializer(repay_list).to_dict()
        return {'msg': 'success', 'data': data}

    def post(self):
        """还款到指定的某个还款计划的某一期"""
        rp = RequestParser()
        rp.add_argument('repay_id')  # 还款计划的ID
        rp.add_argument('repayAmount')  # 当期应该还款的金额

        args = rp.parse_args()
        repay_id = int(args.get('repay_id'))
        repay_amoney = float(args.get('repayAmount'))

        # 得到当前的用户
        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        # 判断用户的账户余额是否足够还款
        if user.accountInfo.balance < repay_amoney:
            return {'message': '账户可用余额不足', 'code': 20005}
        else:
            # 扣除余额
            # 用户.账户.账户可用余额 = 账户可用余额 - 当期应该还款的金额
            user.accountInfo.balance = float(user.accountInfo.balance) - repay_amoney
            # 根据还款计划的ID查询具体的还款计划
            repay = Debtor_repay.query.filter(Debtor_repay.id == repay_id).first()
            # 更改还款状态  0未还款 1已还款
            repay.isReturned = 1
            # 记录还款的日期(为当前系统时间)
            repay.recordDate = datetime.datetime.now()
            # 提交至数据库
            db.session.commit()
            return {'msg': 'success'}
